package com.example.jnihook

import android.content.Intent
import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.example.jnihook.databinding.ActivityMainBinding
import com.pika.jnihook.JniHook
import java.lang.reflect.Method

class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding
    private var logEnable:Boolean = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        // 初始化hook
        JniHook.jniHookInit()

//        val hookMethod = MainActivity::class.java.getDeclaredMethod("testJniHook",Int::class.java,Int::class.java,String::class.java,String::class.java)
        val hookMethod = Log::class.java.getDeclaredMethod(
            "println_native",
            Int::class.java,
            Int::class.java,
            String::class.java,
            String::class.java
        )
//        val methods = Log::class.java.methods
//        methods.forEach {
//            Log.i("hello",it.name)
//        }

        binding.originalCall.setOnClickListener {
            // 正常调用函数
//            val testJniHook = testJniHook(0,0,"TAG","jni param")
//            Log.e("hello", "testJniHook is $testJniHook")
            val ret = Log.i("hello","测试Log");
        }
        binding.jnihook.setOnClickListener {
//            hooktest(hookMethod,true)
            logEnable = !logEnable
            hookAndroidLogNative(hookMethod,logEnable)
        }

        binding.unhook.setOnClickListener {
//            unhooktest(hookMethod)
            unHookAndroidLogNative(hookMethod)
        }

        binding.entry.setOnClickListener {
            startActivity(Intent(this, DispatchTableHook::class.java))
        }

    }

    companion object {
        init {
            System.loadLibrary("jnihooktest")
        }
    }

    // 需要hook的函数
    external fun testJniHook(a:Int,b:Int,tag:String,msg: String):Int

    // 替换的函数
    external fun hooktest(method: Method,enable:Boolean):Int
    external fun unhooktest(method: Method)

    external fun hookAndroidLogNative(method: Method,enable: Boolean):Int

    external fun unHookAndroidLogNative(method: Method)

}